package com.xxc.hs.fragment;

import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import cn.com.newland.nle_sdk.responseEntity.SensorReaTimeData;
import cn.com.newland.nle_sdk.responseEntity.base.BaseResponseEntity;
import cn.com.newland.nle_sdk.util.CloudService;
import cn.com.newland.nle_sdk.util.CloudServiceListener;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.xxc.hs.R;
import com.xxc.hs.bean.CloudInfo;
import com.xxc.hs.bean.WaterDataInfo;
import com.xxc.hs.db.WaterDataHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

@SuppressWarnings("ALL")
public class WaterFragment extends Fragment {
    private static final String TAG = "WaterFragment";
    public static boolean modelIsRunnig = false;        //自动投喂和自动增氧是否打开 - 是否开启自动模式
    private View view;
    private Toolbar toolbar;
    private CardView cardTemp, cardLevel, cardDo, cardPh, cardTurbidity;
    private TextView tvTempValue, tvTempStatus, tvLevelValue, tvLevelStatus;
    private TextView tvDoValue, tvDoStatus, tvPhValue, tvPhStatus, tvTurbidityValue, tvTurbidityStatus;
    private CardView cardAerator, cardFeeder, cardPump;
    private TextView tvAeratorStatus, tvFeederStatus, tvPumpStatus;
    private Switch switchAutoMode;
    private ImageView switchAerator, switchFeeder, switchPump;
    private LineChart chart;
    private Timer timer;
    private CloudService cloudService;
    private WaterDataHelper dataHelper;
    private final int REFRESH_INTERVAL = 10000;      //10秒刷新一次
    private Handler handler;
    private boolean isRefreshing = false;
    private long firstRefreshTime = 0; // 首次刷新时间戳
    private ArrayList<Entry> tempEntries = new ArrayList<>();    // 水温
    private ArrayList<Entry> doEntries = new ArrayList<>();      // 溶解氧
    private ArrayList<Entry> levelEntries = new ArrayList<>();   // 水位
    private ArrayList<Entry> turbidityEntries = new ArrayList<>(); // 浊度
    private ArrayList<Entry> phEntries = new ArrayList<>();      // PH值

    // 自动模式标志
    private boolean isAutoMode = false;
    private boolean aeratorControlEnabled = false;
    private boolean feederControlEnabled = false;
    private boolean pumpControlEnabled = false;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        try {
            view = inflater.inflate(R.layout.fragment_water, container, false);
            if (CloudInfo.getCloudService() == null) {
                CloudInfo.setCloudService();
            }

            initView();
            enableDeviceControls(false);
            setupDeviceSwitchListeners();
            // 初始化数据库帮助类
            dataHelper = WaterDataHelper.getInstance(requireContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        try {
            if (CloudInfo.getCloudService() != null) {
                cloudService = CloudInfo.getCloudService();
            }
            // 设置自动模式开关监听
            setupAutoModeListener();
            setupRefreshTimer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 设置自动模式开关监听
     */
    private void setupAutoModeListener() {
        switchAutoMode.setOnCheckedChangeListener((buttonView, isChecked) -> {
            isAutoMode = isChecked;
            if (isAutoMode) {
                // 进入自动模式
                modelIsRunnig = true;
                enableDeviceControls(true);
            } else {
                // 进入手动模式
                modelIsRunnig = false;
                enableDeviceControls(false);
            }
        });
    }


    /**
     * 启用或禁用设备控制
     */
    private void enableDeviceControls(boolean enable) {
        if (enable) {
            switchAerator.setVisibility(View.INVISIBLE);
            switchFeeder.setVisibility(View.INVISIBLE);
            switchPump.setVisibility(View.INVISIBLE);
        } else {
            switchAerator.setVisibility(View.VISIBLE);
            switchFeeder.setVisibility(View.VISIBLE);
            switchPump.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 获取数据
     */
    private void getData() {
        cloudService.getSensorsRealTimeData(CloudInfo.ProjectId, new CloudServiceListener<BaseResponseEntity<List<SensorReaTimeData>>>() {
            @Override
            protected void onResponse(BaseResponseEntity<List<SensorReaTimeData>> listBaseResponseEntity) {
                if (listBaseResponseEntity.getStatus() != 0) {
                    Log.e(TAG, "云服务数据获取失败");
                    return;
                }
                List<SensorReaTimeData> dataList = listBaseResponseEntity.getResultObj();

                for (SensorReaTimeData data : dataList) {
                    String apiTag = data.getApiTag();
                    String value = data.getValue();
                    // 根据apiTag更新对应UI控件
                    updateSensorUI(apiTag, value);
                }

                // 更新图表数据
                updateChartData(dataList);

                //保存数据到数据库
                saveSensorDataToDatabase(dataList);

                if (isAutoMode) {
                    executeAutoControlStrategies(dataList);
                }

            }
        });
    }


    /**
     * 执行自动控制策略
     */
    private void executeAutoControlStrategies(List<SensorReaTimeData> sensorData) {
        float dissolvedOxygen = 0;
        float turbidity = 0;
        float waterLevel = 0;

        // 解析传感器数据
        for (SensorReaTimeData data : sensorData) {
            String apiTag = data.getApiTag();
            if (!apiTag.equals(CloudInfo.UHF)) {
                float value = Float.parseFloat(data.getValue());
                switch (apiTag) {
                    case CloudInfo.DISSOLVED:
                        dissolvedOxygen = value;
                        break;
                    case CloudInfo.TURBIDITY:
                        turbidity = value;
                        break;
                    case CloudInfo.WATERLEVEL:
                        waterLevel = value;
                }
            }
        }

        //自动打开水泵：水位过低时候
        if (waterLevel < 15){
            controlDevice(CloudInfo.WATERLEVEL, true);
        }else {
            controlDevice(CloudInfo.WATERLEVEL, false);
        }

        // 自动控制增氧泵：溶氧量<5时打开
        if (dissolvedOxygen < 5) {
            controlDevice(CloudInfo.ZENGYANGBENG, true);
        } else {
            controlDevice(CloudInfo.ZENGYANGBENG, false);
        }

        // 自动控制投料机：早晨6-7点或晚上7-8点打开
        if (isFeedingTime()) {
            controlDevice(CloudInfo.TOULIAOJI, true);

        } else {
            controlDevice(CloudInfo.TOULIAOJI, false);
        }

        // 自动控制水泵：浊度>20时打开
        if (turbidity > 10) {
            controlDevice(CloudInfo.SHUIBENG, true);
        } else {
            controlDevice(CloudInfo.SHUIBENG, false);
        }

    }


    /**
     * 判断是否为投料时间（早晨6-7点或晚上7-8点）
     */
    private boolean isFeedingTime() {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);

        return (hour >= 6 && hour < 7) || (hour >= 19 && hour < 20);
    }


    /**
     * 控制设备
     */
    private void controlDevice(final String deviceId, final boolean command) {
        // 在后台线程执行设备控制，不阻塞UI
        new Thread(new Runnable() {
            @Override
            public void run() {
                cloudService.control(CloudInfo.GatewayId, deviceId, command, new CloudServiceListener<BaseResponseEntity>() {
                    @Override
                    protected void onResponse(BaseResponseEntity baseResponseEntity) {
                    }
                });
                updateDeviceStatus(deviceId, command);
            }
        }).start();
    }


    /**
     * 更新设备状态UI
     */
    private void updateDeviceStatus(String deviceId, boolean state) {
        requireActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switch (deviceId) {
                    case CloudInfo.ZENGYANGBENG:
                        if (state) {
                            switchAerator.setImageResource(R.drawable.btn_list_switch_on);
                            tvAeratorStatus.setText("已打开");
                            tvAeratorStatus.setTextColor(Color.GREEN);
                        } else {
                            switchAerator.setImageResource(R.drawable.btn_list_switch_off);
                            tvAeratorStatus.setText("已关闭");
                            tvAeratorStatus.setTextColor(Color.GRAY);
                        }
                        break;
                    case CloudInfo.TOULIAOJI:
                        if (state) {
                            switchFeeder.setImageResource(R.drawable.btn_list_switch_on);
                            tvFeederStatus.setText("已打开");
                            tvFeederStatus.setTextColor(Color.GREEN);
                        } else {
                            switchFeeder.setImageResource(R.drawable.btn_list_switch_off);
                            tvFeederStatus.setText("已关闭");
                            tvFeederStatus.setTextColor(Color.GRAY);
                        }
                        break;
                    case CloudInfo.SHUIBENG:
                        if (state) {
                            switchPump.setImageResource(R.drawable.btn_list_switch_on);
                            tvPumpStatus.setText("已打开");
                            tvPumpStatus.setTextColor(Color.GREEN);
                        } else {
                            switchPump.setImageResource(R.drawable.btn_list_switch_off);
                            tvPumpStatus.setText("已关闭");
                            tvPumpStatus.setTextColor(Color.GRAY);
                        }
                        break;
                    default:
                        break;
                }
            }
        });


    }


    /**
     * 设置设备开关监听
     */
    private void setupDeviceSwitchListeners() {
        // 增氧泵开关监听
        switchAerator.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aeratorControlEnabled = !aeratorControlEnabled;
                if (aeratorControlEnabled)
                    controlDevice(CloudInfo.ZENGYANGBENG, true);
                else
                    controlDevice(CloudInfo.ZENGYANGBENG, false);
            }
        });


        // 投料机开关监听
        switchFeeder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                feederControlEnabled = !feederControlEnabled;
                if (feederControlEnabled)
                    controlDevice(CloudInfo.TOULIAOJI, true);
                else
                    controlDevice(CloudInfo.TOULIAOJI, false);
            }
        });

        // 水泵开关监听
        switchPump.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pumpControlEnabled = !pumpControlEnabled;
                if (pumpControlEnabled)
                    controlDevice(CloudInfo.SHUIBENG, true);
                else
                    controlDevice(CloudInfo.SHUIBENG, false);
            }
        });
    }


    /**
     * 将传感器数据保存到数据库
     */
    private void saveSensorDataToDatabase(List<SensorReaTimeData> sensorData) {
        // 创建水质数据对象
        WaterDataInfo waterData = new WaterDataInfo();

        // 设置时间戳
        waterData.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        // 解析传感器数据并设置到水质数据对象
        for (SensorReaTimeData data : sensorData) {
            String apiTag = data.getApiTag();
            String value = data.getValue();

            switch (apiTag) {
                case CloudInfo.WATERTEMP:
                    waterData.setWaterTemp(value);
                    break;
                case CloudInfo.DISSOLVED:
                    waterData.setDissolved(value);
                    break;
                case CloudInfo.WATERLEVEL:
                    waterData.setWaterLevel(value);
                    break;
                case CloudInfo.TURBIDITY:
                    waterData.setTurbidity(value);
                    break;
                case CloudInfo.PH:
                    waterData.setPh(value);
                    break;
                case CloudInfo.YULV:
                    waterData.setYuLv(value);
                    break;
            }
        }

        // 保存到数据库（在后台线程执行）
        new Thread(() -> {
            long result = dataHelper.InsertWaterData(waterData);
            if (result != -1) {
                Log.d(TAG, "数据保存成功，ID: " + result);
            } else {
                Log.e(TAG, "数据保存失败");
            }
        }).start();
    }

    /**
     * 根据传感器API标签更新对应的UI控件
     */
    private void updateSensorUI(String apiTag, String values) {
        if (apiTag.equals(CloudInfo.UHF)) {
            return;
        }

        try {
            BigDecimal bd = new BigDecimal(values).setScale(3, RoundingMode.HALF_UP);
            float value = bd.floatValue();

            // 确保在UI线程执行
            requireActivity().runOnUiThread(() -> {
                switch (apiTag) {
                    case CloudInfo.WATERTEMP:
                        tvTempValue.setText(value + "℃");
                        updateStatusIndicator(tvTempStatus, Double.parseDouble(String.valueOf(value)), 15, 30);
                        break;

                    case CloudInfo.WATERLEVEL:
                        tvLevelValue.setText(value + "cm");
                        updateStatusIndicator(tvLevelStatus, Double.parseDouble(String.valueOf(value)), 15, 40);
                        break;

                    case CloudInfo.DISSOLVED:
                        tvDoValue.setText(value + "mg/L");
                        updateStatusIndicator(tvDoStatus, Double.parseDouble(String.valueOf(value)), 5, Double.MAX_VALUE);
                        break;

                    case CloudInfo.PH:
                        tvPhValue.setText(value + "");
                        updateStatusIndicator(tvPhStatus, Double.parseDouble(String.valueOf(value)), 6, 8);
                        break;

                    case CloudInfo.TURBIDITY:
                        tvTurbidityValue.setText(value + "NTU");
                        updateStatusIndicator(tvTurbidityStatus, Double.parseDouble(String.valueOf(value)), 0, 20);
                        break;
                    default:
                        break;
                }
            });
        } catch (NumberFormatException | NullPointerException e) {
            Log.e(TAG, "数据解析错误: " + e.getMessage());
        }
    }


    /**
     * 更新状态指示器（正常/警告/危险）
     */
    private void updateStatusIndicator(TextView statusView, double value, double min, double max) {
        int colorResId;
        String statusText;

        if (value < min) {
            colorResId = R.color.status_warning;
            statusText = "过低";
        } else if (value > max) {
            colorResId = R.color.status_danger;
            statusText = "过高";
        } else {
            colorResId = R.color.status_normal;
            statusText = "正常";
        }

        statusView.setText(statusText);
        statusView.setTextColor(getResources().getColor(colorResId));
    }


    /**
     * 更新图表数据 - 显示水温、溶解氧、水位、浊度和PH值
     */
    private void updateChartData(List<SensorReaTimeData> sensorData) {
        // 收集各传感器数据点
        if (firstRefreshTime == 0) {
            firstRefreshTime = System.currentTimeMillis();
        }

        long currentTime = System.currentTimeMillis();

        // 解析传感器数据
        for (SensorReaTimeData data : sensorData) {
            String apiTag = data.getApiTag();
            float value = 0;
            if (!apiTag.equals(CloudInfo.UHF)) {
                value = Float.parseFloat(data.getValue());
            }
            // 根据API标签添加到对应数据集合
            switch (apiTag) {
                case CloudInfo.WATERTEMP:
                    tempEntries.add(new Entry(currentTime, value));
                    break;
                case CloudInfo.DISSOLVED:
                    doEntries.add(new Entry(currentTime, value));
                    break;
                case CloudInfo.WATERLEVEL: // 假设水位API标签是waterLevel
                    levelEntries.add(new Entry(currentTime, value));
                    break;
                case CloudInfo.TURBIDITY: // 假设浊度API标签是turbidity
                    turbidityEntries.add(new Entry(currentTime, value));
                    break;
                case CloudInfo.PH: // 假设PH值API标签是phValue
                    phEntries.add(new Entry(currentTime, value));
                    break;
            }
        }

        //限制数据点
        limitDataPoints(tempEntries, doEntries, levelEntries, turbidityEntries, phEntries);

        // 创建各传感器数据集
        LineDataSet tempDataSet = createDataSet(tempEntries, "水温", Color.BLUE);
        LineDataSet doDataSet = createDataSet(doEntries, "溶解氧", Color.RED);
        LineDataSet levelDataSet = createDataSet(levelEntries, "水位", Color.GREEN);
        LineDataSet turbidityDataSet = createDataSet(turbidityEntries, "浊度", Color.MAGENTA);
        LineDataSet phDataSet = createDataSet(phEntries, "PH值", Color.YELLOW);

        // 创建数据对象
        LineData lineData = new LineData(tempDataSet, doDataSet, levelDataSet, turbidityDataSet, phDataSet);

        // 配置图表样式
        configureChartAppearance();

        // 设置图表数据
        chart.setData(lineData);
        chart.invalidate(); // 刷新图表

    }

    /**
     * 限制数据点数量，只保留最近的N个点
     */
    private void limitDataPoints(ArrayList<Entry>... dataSets) {
        final int MAX_POINTS = 20; // 最多显示20个数据点
        for (ArrayList<Entry> dataSet : dataSets) {
            while (dataSet.size() > MAX_POINTS) {
                dataSet.remove(0); // 移除最旧的数据点
            }
        }
    }

    /**
     * 创建数据集的辅助方法
     */
    private LineDataSet createDataSet(ArrayList<Entry> entries, String label, int color) {
        LineDataSet dataSet = new LineDataSet(entries, label);
        dataSet.setColor(color);
        dataSet.setValueTextColor(color);
        dataSet.setLineWidth(2f);
        dataSet.setCircleRadius(4f);
        dataSet.setDrawCircleHole(false);
        dataSet.setDrawValues(true);
        dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); // 使用平滑曲线
        return dataSet;
    }

    /**
     * 配置图表外观
     */
    private void configureChartAppearance() {
        // 配置图表整体外观
        chart.getDescription().setEnabled(true);
        chart.getDescription().setText("传感器数据趋势");
        chart.getDescription().setTextSize(12f);

        // 配置图例
        Legend legend = chart.getLegend();
        legend.setEnabled(true);
        legend.setTextSize(12f);
        legend.setForm(Legend.LegendForm.CIRCLE);

        // 配置X轴
        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                long relativeTime = (long) value - firstRefreshTime;
                int seconds = (int) (relativeTime / 1000) % 60;
                int minutes = (int) (relativeTime / (1000 * 60)) % 60;
                return String.format("%02d:%02d", minutes, seconds);
            }
        });

        // 配置Y轴
        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setAxisMinimum(0f);

        // 禁用右侧Y轴
        YAxis rightAxis = chart.getAxisRight();
        rightAxis.setEnabled(false);
    }


    /**
     * 设置定时刷新任务（使用Timer方式）
     */
    private void setupRefreshTimer() {
        timer = new Timer(true);
        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    getData(); // 执行数据刷新
                }
            }
        };
    }

    /**
     * 开始定时刷新
     */
    private void startRefreshTimer() {
        try {
            if (timer != null && !isRefreshing) {
                isRefreshing = true;
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        // 发送消息到Handler处理UI更新
                        handler.sendEmptyMessage(1);
                    }
                }, 0, REFRESH_INTERVAL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止定时刷新
     */
    private void stopRefreshTimer() {
        try {
            if (timer != null) {
                isRefreshing = false;
                timer.cancel();
                timer.purge();
                timer = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        // 初始化顶部标题栏
        toolbar = view.findViewById(R.id.toolbar);

        // 初始化数据监控卡片
        cardTemp = view.findViewById(R.id.card_temp);
        cardLevel = view.findViewById(R.id.card_level);
        cardDo = view.findViewById(R.id.card_do);
        cardPh = view.findViewById(R.id.card_ph);
        cardTurbidity = view.findViewById(R.id.card_turbidity);

        // 初始化数据监控文本
        tvTempValue = view.findViewById(R.id.tv_temp_value);
        tvTempStatus = view.findViewById(R.id.tv_temp_status);
        tvLevelValue = view.findViewById(R.id.tv_level_value);
        tvLevelStatus = view.findViewById(R.id.tv_level_status);
        tvDoValue = view.findViewById(R.id.tv_do_value);
        tvDoStatus = view.findViewById(R.id.tv_do_status);
        tvPhValue = view.findViewById(R.id.tv_ph_value);
        tvPhStatus = view.findViewById(R.id.tv_ph_status);
        tvTurbidityValue = view.findViewById(R.id.tv_turbidity_value);
        tvTurbidityStatus = view.findViewById(R.id.tv_turbidity_status);

        // 初始化设备控制卡片
        cardAerator = view.findViewById(R.id.card_aerator);
        cardFeeder = view.findViewById(R.id.card_feeder);
        cardPump = view.findViewById(R.id.card_pump);

        // 初始化设备状态文本和开关
        tvAeratorStatus = view.findViewById(R.id.tv_aerator_status);
        tvFeederStatus = view.findViewById(R.id.tv_feeder_status);
        tvPumpStatus = view.findViewById(R.id.tv_pump_status);
        switchAerator = view.findViewById(R.id.switch_aerator);
        switchFeeder = view.findViewById(R.id.switch_feeder);
        switchPump = view.findViewById(R.id.switch_pump);
        switchAutoMode = view.findViewById(R.id.switch_auto_mode);

        // 初始化图表
        chart = view.findViewById(R.id.chart);
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            startRefreshTimer();     // 在Fragment可见时开始刷新
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        try {
            stopRefreshTimer();     // 在Fragment不可见时停止刷新，节省资源
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            stopRefreshTimer();

            if (null != handler) {
                handler.removeCallbacksAndMessages(null);
                handler = null;
            }

            if (cloudService != null) {
                cloudService = null;
            }

            if (chart != null) {
                chart.clear();
                chart = null;
            }

            if (tempEntries != null) tempEntries.clear();
            if (doEntries != null) doEntries.clear();
            if (levelEntries != null) levelEntries.clear();
            if (turbidityEntries != null) turbidityEntries.clear();
            if (phEntries != null) phEntries.clear();

            if (dataHelper != null) {
                dataHelper.close();
                dataHelper = null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}